package com.clive.ttweb.excption;

import com.clive.ttweb.vo.DishResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;


@ControllerAdvice
//@ControllerAdvice用是给Controller控制器添加统一的操作或处理。
public class GlobalException {
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public DishResult error(Exception e){
        e.printStackTrace();
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
            List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
            FieldError error = fieldErrors.get(0);
            String msg = error.getDefaultMessage();
            return DishResult.error(msg);
        }
        return DishResult.error(e.getMessage());
    }
}
